import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
import cors from '@koa/cors';
// import Sequelize from 'sequelize';


const app = new Koa()
const router = new Router()
app.use(cors())
app.use(bodyParser())


// 获取所有志愿活动
router.get('/api/activities', async (ctx) => {
  try {
    const activities = await getAll();
    ctx.body = activities;
  } catch (error) {
    ctx.status = 500;
    ctx.body = { message: 'Database error' };
  }
});

// 创建志愿活动
router.post('/api/activities', async (ctx) => {
  try {
    const result = await create(ctx.request.body);
    ctx.body = { message: 'Activity created', id: result.insertId };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { message: 'Database error' };
  }
});

// 更新志愿活动
router.put('/api/activities/:id', async (ctx) => {
  try {
    const result = await update(ctx.request.body, ctx.params.id);
    if (result.affectedRows === 0) {
      ctx.status = 404;
      ctx.body = { message: 'Activity not found' };
    } else {
      ctx.body = { message: 'Activity updated' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { message: 'Database error' };
  }
});

// 删除志愿活动
router.delete('/api/activities/:id', async (ctx) => {
  try {
    const result = await remove(ctx.params.id);
    if (result.affectedRows === 0) {
      ctx.status = 404;
      ctx.body = { message: 'Activity not found' };
    } else {
      ctx.body = { message: 'Activity deleted' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { message: 'Database error' };
  }
});

app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());

const port = 3000;
app.listen(port);
console.log(`服务器运行于：http://localhost:${port}`);